<!-- V-webapp/src/views/ActivityDetailView.vue -->
<template>
  <div class="activity-detail-page">
    <!-- 顶部沉浸式封面 - 修复尺寸 -->
    <div class="activity-cover">
      <img :src="getActivityImage(activity.cover_image)" class="cover-image" />
      <div class="cover-overlay">
        <el-tag :type="getStatusType(activity.status)" class="status-tag">
          {{ getStatusText(activity.status) }}
        </el-tag>
      </div>
    </div>

    <!-- 活动基本信息 -->
    <div class="activity-info-section">
      <h1 class="activity-title">{{ activity.title }}</h1>
      <div class="activity-meta">
        <div class="meta-item">
          <el-icon><User /></el-icon>
          <span>{{ activity.anchor?.anchor_name || '未知主播' }}</span>
        </div>
        <div class="meta-item">
          <el-icon><Clock /></el-icon>
          <span>{{ formatTime(activity.start_time) }}</span>
        </div>
        <div class="meta-item">
          <el-icon><Location /></el-icon>
          <span>{{ activity.location || '线上活动' }}</span>
        </div>
      </div>

      <!-- 预约统计 -->
      <div class="registration-stats">
        <div class="stat-item">
          <div class="stat-number">{{ activity.current_participants || 0 }}</div>
          <div class="stat-label">已预约</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">{{ activity.max_participants || '无限制' }}</div>
          <div class="stat-label">名额限制</div>
        </div>
      </div>
    </div>

    <!-- Tab标签页 -->
    <el-tabs v-model="activeTab" class="detail-tabs">
      <el-tab-pane label="活动详情" name="detail">
        <div class="tab-content">
          <h3>活动介绍</h3>
          <div class="activity-description">{{ activity.description || '暂无活动介绍' }}</div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="留言板" name="comments">
        <div class="tab-content">
          <!-- 留言输入 -->
          <div class="comment-input-section" v-if="isLoggedIn">
            <el-input
              v-model="newComment"
              type="textarea"
              :rows="3"
              placeholder="留下你的评论..."
              maxlength="200"
              show-word-limit
            />
            <el-button 
              type="primary" 
              class="submit-comment-btn"
              @click="submitComment"
              :loading="commentLoading"
            >
              发表评论
            </el-button>
          </div>
          <div v-else class="login-tip">
            <p>请先登录后发表评论</p>
            <el-button type="primary" @click="$router.push('/login')">立即登录</el-button>
          </div>

          <!-- 评论列表 -->
          <div class="comments-list">
            <div v-for="comment in comments" :key="comment.id" class="comment-item">
              <div class="comment-header">
                <img :src="comment.user.avatar || '/default-avatar.jpg'" class="user-avatar" />
                <div class="user-info">
                  <div class="username">{{ comment.user.name }}</div>
                  <div class="comment-time">{{ formatCommentTime(comment.createdAt) }}</div>
                </div>
              </div>
              <div class="comment-content">{{ comment.content }}</div>
            </div>
            <div v-if="comments.length === 0" class="empty-state">
              <el-icon><ChatDotRound /></el-icon>
              <p>暂无评论，快来抢沙发吧~</p>
            </div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 底部操作栏 -->
    <div class="bottom-action-bar">
      <el-button 
        class="follow-btn" 
        :type="isFollowing ? 'info' : 'primary'" 
        @click="toggleFollow"
      >
        <el-icon><Star /></el-icon>
        {{ isFollowing ? '已关注' : '关注主播' }}
      </el-button>
      
      <el-button 
        type="primary" 
        class="register-btn" 
        :disabled="!canRegister"
        @click="handleRegister"
        :loading="registerLoading"
      >
        <el-icon><Calendar /></el-icon>
        {{ getRegisterButtonText() }}
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  User, Clock, Location, Document, 
  ChatDotRound, Star, Calendar 
} from '@element-plus/icons-vue'
import { getActivityDetail, registerActivity } from '@/api/activities'

// 导入本地活动图片
import liangzhounian from '@/assets/images/liangzhounian.png'
import activity150W from '@/assets/images/150W.jpg'
import defaultActivityImg from '@/assets/images/S1.jpg'

const route = useRoute()
const router = useRouter()
const activityId = parseInt(route.params.id as string)

// 响应式数据
const activity = ref<any>({})
const activeTab = ref('detail')
const newComment = ref('')
const comments = ref<any[]>([])
const isFollowing = ref(false)
const registerLoading = ref(false)
const commentLoading = ref(false)

// 图片映射表
const imageMap = {
  'liangzhounian.png': liangzhounian,
  '150W.jpg': activity150W,
  'S1.jpg': defaultActivityImg
}

// 获取活动图片
const getActivityImage = (coverImage: string) => {
  if (!coverImage) return defaultActivityImg
  return imageMap[coverImage] || defaultActivityImg
}

// 计算属性
const isLoggedIn = computed(() => {
  return !!localStorage.getItem('token')
})

const canRegister = computed(() => {
  return activity.value.status === 'published' && !activity.value.isRegistered
})

// 状态映射函数 - 根据你的数据库状态值
const getStatusText = (status: string) => {
  const statusMap: any = {
    'pending': '待发布',
    'published': '预约中', 
    'ongoing': '进行中',
    'completed': '已结束',
    'cancelled': '已取消'
  }
  return statusMap[status] || status
}

const getStatusType = (status: string) => {
  const statusMap: any = {
    'pending': 'info',
    'published': 'warning',
    'ongoing': 'success',
    'completed': 'info',
    'cancelled': 'danger'
  }
  return statusMap[status] || 'info'
}

// 方法
const loadActivityDetail = async () => {
  try {
    const result = await getActivityDetail(activityId)
    console.log('活动详情数据:', result)
    activity.value = result.data || {}
  } catch (error) {
    ElMessage.error('加载活动详情失败')
    console.error('活动详情加载错误:', error)
  }
}

const formatTime = (time: string) => {
  if (!time) return '时间待定'
  return new Date(time).toLocaleString('zh-CN')
}

const formatCommentTime = (time: string) => {
  return new Date(time).toLocaleDateString('zh-CN')
}

const getRegisterButtonText = () => {
  if (activity.value.isRegistered) return '已预约'
  if (activity.value.status === 'completed') return '已结束'
  if (activity.value.status === 'cancelled') return '已取消'
  if (activity.value.status === 'ongoing') return '进行中'
  if (activity.value.status === 'pending') return '待发布'
  return '立即预约'
}

const handleRegister = async () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录后再预约')
    router.push(`/login?redirect=${encodeURIComponent(route.fullPath)}`)
    return
  }

  try {
    registerLoading.value = true
    await registerActivity(activityId)
    activity.value.isRegistered = true
    activity.value.current_participants = (activity.value.current_participants || 0) + 1
    ElMessage.success('预约成功！')
  } catch (error: any) {
    ElMessage.error(error.message || '预约失败')
  } finally {
    registerLoading.value = false
  }
}

const toggleFollow = () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录后再关注')
    router.push(`/login?redirect=${encodeURIComponent(route.fullPath)}`)
    return
  }
  isFollowing.value = !isFollowing.value
  ElMessage.success(isFollowing.value ? '关注成功' : '已取消关注')
}

const submitComment = async () => {
  if (!newComment.value.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }

  try {
    commentLoading.value = true
    // 这里调用评论API
    ElMessage.success('评论发表成功')
    newComment.value = ''
  } catch (error) {
    ElMessage.error('评论发表失败')
  } finally {
    commentLoading.value = false
  }
}

// 生命周期
onMounted(() => {
  loadActivityDetail()
})
</script>

<style scoped>
.activity-detail-page {
  background: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 100px; /* 增加底部空间 */
}

/* 修复图片容器 - 移除绝对定位的覆盖层问题 */
.activity-cover {
  position: relative;
  height: 200px;
  overflow: hidden;
  background: #e0e0e0;
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.cover-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(to bottom, transparent 60%, rgba(0,0,0,0.3)); /* 减少透明度 */
  display: flex;
  align-items: flex-end;
  justify-content: flex-start;
  padding: 16px;
}

.status-tag {
  font-size: 14px;
  font-weight: 600;
  background: rgba(255, 255, 255, 0.9); /* 让标签更清晰 */
  border: none;
}

.activity-info-section {
  background: white;
  padding: 20px;
  margin-top: 0;
  position: relative; /* 确保正常文档流 */
  z-index: 1; /* 确保在图片之上 */
}

.activity-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
  line-height: 1.4;
}

.activity-meta {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 20px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
  font-size: 14px;
}

.registration-stats {
  display: flex;
  gap: 30px;
  padding: 15px 0;
  border-top: 1px solid #f0f0f0;
}

.stat-item {
  text-align: center;
}

.stat-number {
  font-size: 18px;
  font-weight: bold;
  color: #409eff;
}

.stat-label {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.detail-tabs {
  background: white;
  margin-top: 10px;
  position: relative;
  z-index: 1;
}

.tab-content {
  padding: 20px;
  min-height: 200px;
}

.activity-description {
  line-height: 1.6;
  color: #333;
  white-space: pre-wrap;
}

.comment-input-section {
  margin-bottom: 20px;
}

.submit-comment-btn {
  margin-top: 10px;
  width: 100%;
}

.login-tip {
  text-align: center;
  padding: 30px;
  color: #666;
}

.comments-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.comment-item {
  padding: 15px;
  background: #f9f9f9;
  border-radius: 8px;
}

.comment-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.user-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  object-fit: cover;
}

.user-info {
  flex: 1;
}

.username {
  font-weight: bold;
  font-size: 14px;
}

.comment-time {
  font-size: 12px;
  color: #999;
}

.comment-content {
  color: #333;
  line-height: 1.5;
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: #999;
}

.empty-state .el-icon {
  font-size: 40px;
  margin-bottom: 10px;
}

/* 修复底部操作栏 */
.bottom-action-bar {
  position: fixed;
  bottom: 60px; /* 在底部导航栏之上 */
  left: 50%;
  transform: translateX(-50%);
  width: calc(100% - 32px);
  max-width: 480px;
  background: white;
  padding: 12px 16px;
  display: flex;
  gap: 12px;
  box-shadow: 0 -2px 20px rgba(0,0,0,0.15);
  z-index: 1000;
  border-radius: 12px;
  margin: 0 auto;
}

.follow-btn, .register-btn {
  flex: 1;
  height: 44px;
  border-radius: 8px;
  font-weight: 600;
}

.register-btn {
  flex: 2;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .activity-cover {
    height: 180px;
  }
  
  .activity-info-section {
    padding: 16px;
  }
  
  .activity-title {
    font-size: 18px;
  }
  
  .tab-content {
    padding: 16px;
  }
  
  .bottom-action-bar {
    bottom: 60px;
    width: calc(100% - 24px);
    padding: 10px 12px;
  }
  
  .follow-btn, .register-btn {
    height: 42px;
    font-size: 14px;
  }
}

/* 确保内容不会被底部操作栏遮挡 */
@media (max-width: 480px) {
  .activity-detail-page {
    padding-bottom: 120px; /* 为操作栏留更多空间 */
  }
  
  .bottom-action-bar {
    bottom: 50px;
  }
}
</style>